package com.ml.ws.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class IMClient {

	public static void main(String[] args) {

		String addr = "http://localhost:8080/webservice/ws/im/find";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("memberID", "11111");
		map.put("clientID", "222222");
		map.put("j_username", "ml");
		map.put("j_password", "ml");
		try {
			
			addr = "http://localhost:8080/webservice/j_spring_security_check";
			doPost(addr, map);
			map.put("jsessionid", "504911CCFC007795D0B7B072DA2E6ADB");
			addr = "http://localhost:8080/webservice/ws/im/find";
			doGet(addr, map);
//			addr = "http://localhost:8080/webservice/ws/im/create";
//			doPost(addr, map);
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	public static void doGet(String surl, Map<String, Object> params)
			throws MalformedURLException, IOException {
		
		String paramStr = prepareParam(params);
		if(paramStr != null && paramStr.trim().length() > 0){
			surl +="?"+paramStr;
		}
		URL url = new URL(surl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Content-Type","text/html; charset=UTF-8"); 
		conn.connect();
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		String result = "";
		while((line =br.readLine()) != null){
			result += "\n"+line;
		}
		System.out.println(result);
		br.close();
	}

	public static void doPost(String surl, Map<String, Object> params)
			throws MalformedURLException, IOException {
		URL url = new URL(surl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		String paramStr = prepareParam(params);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		OutputStream os = conn.getOutputStream();
		os.write(paramStr.toString().getBytes("UTF-8"));
		os.close();
		
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
		String line;
		String result = "";
		while((line = br.readLine()) != null){
			result += "\n"+line;
		}
		System.out.println(result);
		br.close();
	}

	private static String prepareParam(Map<String, Object> paramMap) {
		StringBuffer sb = new StringBuffer();
		if (paramMap.isEmpty()) {
			return "";
		} else {
			for (String key : paramMap.keySet()) {
				String value = (String) paramMap.get(key);
				if (sb.length() < 1) {
					sb.append(key).append("=").append(value);
				} else {
					sb.append("&").append(key).append("=").append(value);
				}
			}
			return sb.toString();
		}
	}

}
